package com.wh.wisdomsite.xbox.utils.json.impl;

import com.wh.wisdomsite.xbox.utils.json.JosnConverter;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.AnnotationIntrospector;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.xc.JaxbAnnotationIntrospector;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.StringWriter;


/**
 * JSON转换(org.codehaus.jackson接口实现)
 * @Package com.wh.wisdomsite.xbox.utils.json
 * @author 谢泽鹏
 * @date 2014年10月8日 下午4:02:14
 * @Copyright 个人版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2014
 * @version V1.0
 */
public class JackJosnConverter implements JosnConverter {

    private static final Log logger = LogFactory.getLog(JackJosnConverter.class);

    private static final ObjectMapper objectMapper = new ObjectMapper();

    static {
        AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();
        SerializationConfig serializationConfig = objectMapper.getSerializationConfig();
        serializationConfig = serializationConfig.without(SerializationConfig.Feature.WRAP_ROOT_VALUE).withAnnotationIntrospector(introspector);
        objectMapper.setSerializationConfig(serializationConfig);
    }


    /**
     * 将String转换成Object
     * @param string 转换string
     * @param clazz  转换object
     * @param <T>    返回结果
     * @return
     */
    @Override
    public <T> T getObject(String string, Class<T> clazz) {
        try {
            JsonParser jsonParser = objectMapper.getJsonFactory().createJsonParser(string);
            return jsonParser.readValueAs(clazz);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("getObject->>Convert String " + string + "to an Object " + clazz.getName() + " that " + "causes an error!" + string + "转化为对象" + clazz.getName() + "时错误: " + e.getMessage());
            throw new RuntimeException(e);
        }
    }

    /**
     * 将Objcet转换成String
     * @param object 转换object
     * @return 返回结果
     */
    @Override
    public String getString(Object object) {
        StringWriter stringWriter = new StringWriter();
        try {
            JsonGenerator jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(stringWriter);
            objectMapper.writeValue(jsonGenerator, object);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("getObject->>将对象" + object.getClass() + "流化为字符串错误 : " + e.getMessage());
            throw new RuntimeException(e);
        }
        return stringWriter.getBuffer().toString();
    }
}
